import { login, logout, getInfo } from "@/api/user";
import {
  getToken,
  setToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeName,
  setName,
  setAvatar,
  clearLocalStorage
} from "@/utils/auth";
import router, { resetRouter } from "@/router";
import { Message } from "element-ui";

const state = {
  token: getToken(),
  name: "",
  avatar: "",
  introduction: "",
  roles: []
};

const mutations = {
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), pwd: password })
        .then(res => {
          console.log("res");
          console.log(res);
          if (res.code === "2000") {
            const { data } = res;
            //登录用户信息
            console.log("登录", "8888");
            let { token, avatarUrl, userName } = data;
            commit("SET_USERINFO", data);
            commit("SET_TOKEN", token);
            commit("SET_NAME", userName);
            // commit('SET_AVATAR', data.avatar)
            commit("SET_AVATAR", avatarUrl);
            removeToken();
            setUserInfo(data);
            setName(userName);
            setAvatar(avatarUrl);
            setToken(token);
            Message({
              type: "success",
              message: "登录成功!"
            });
            resolve(data);
          } else {
            // Message({
            //   type: "error",
            //   message: "用户名或密码错误"
            // });
            reject(res);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response;

          if (!data) {
            reject("Verification failed, please Login again.");
          }

          const { roles, name, avatar, introduction } = data;

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject("getInfo: roles must be a non-null array!");
          }

          commit("SET_ROLES", roles);
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_INTRODUCTION", introduction);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout({})
        .then(res => {
          console.log("res", res);
          if (res.code === "2000") {
            commit("SET_TOKEN", "");
            clearLocalStorage();
            resetRouter();
            dispatch("tagsView/delAllViews", null, { root: true });
            resolve(res);
          } else {
            reject();
          }
          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      removeToken();
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
